<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <title>用户详情</title>
    <style>
        #headPic {
            width: 100px;
            height: 100px;
            border-radius: 50% 50%;
            background: wheat;
            text-align: center;
            line-height: 100px;
            background-size: 100% 100%;
        }

        #headPic:hover {
            cursor: pointer;
        }

        #file {
            display: none;
        }
    </style>
</head>
<body>
<table align="center" border="2">
    <tr>
        <td>头像</td>
        <td>
            <div id="headPic">点我上传头像</div>
            <input type="file" id="file"></td>
    </tr>
    <tr>
        <td>用户名</td>
        <td>${userInfo.username}</td>
    </tr>
    <form action="${pageContext.request.contextPath}/user/edit" method="post">
        <input type="hidden" name="id" value="${userInfo.id}">
        <tr>
            <td>昵称</td>
            <td><input type="text" name="nickname" value="${userInfo.nickname}"></td>
        </tr>
        <tr>
            <td>年龄</td>
            <td><input type="text" name="age" value="${userInfo.age}"></td>
        </tr>
        <tr>
            <td>生日</td>
            <td><input type="date" name="birthday"
                       value="<fmt:formatDate value="${userInfo.birthday}" pattern="yyyy-MM-dd"></fmt:formatDate>"></td>
        </tr>
        <tr>
            <td colspan="2">
                <button>提交</button>
            </td>
        </tr>
    </form>
</table>
<script>
    $(function () {
        console.log('${userInfo.headPic}')
        if ('${userInfo.headPic}' != "") {
            $("#headPic").css("background-image", "url(" + '${userInfo.headPic}' + ")");
            $("#headPic").text("")
        }
        $("#headPic").on("click", function () {
            //当点击头像的时候触发file文件框
            $("#file").click()
        })
        $("#file").on("change", function () {
            let file = $("#file").prop("files")[0];
            let formData = new FormData()
            formData.append("file", file)
            $.ajax({
                url: "${pageContext.request.contextPath}/user/upload",
                type: "post",
                data: formData,
                // 默认情况下会解析成 x-www-form-urlencoded
                // 不去处理请求体数据
                processData: false,
                // 告诉ajax 不许处理请求头
                contentType: false,
                success(res) {
                    console.log(res.url)
                    $("#headPic").css("background-image", "url(" + res.url + ")");
                    $("#file").val("")
                    $("#headPic").text("")
                }
            })
        })
    })
</script>
</body>
</html>
